import configparser
import os
from typing import List, Dict, Any, Optional


class ConfigManager:
    def __init__(self, config_file: str = "settings.ini"):
        self.config_file = config_file
        self.config = configparser.ConfigParser()
        self.xlsx_file_path: Optional[str] = None
        self.display_columns: List[str] = []
        self.filter_conditions: Dict[str, Any] = {}
        
        # 确保配置文件存在
        if not os.path.exists(self.config_file):
            self._create_default_config()
        
        self.load_config()

    def _create_default_config(self) -> None:
        """创建默认配置文件"""
        self.config["XLSX"] = {
            "file_path": "",
            "display_columns": "",
            "filter_conditions": "{}",
            "window_width": "760",
            "window_height": "920",
            "checkbox_cols_per_row": "4",
            "filter_cols_per_row": "3"
        }
        self.save_config()

    def load_config(self) -> None:
        """从配置文件加载配置"""
        self.config.read(self.config_file, encoding='utf-8')
        
        if "XLSX" in self.config:
            xlsx_section = self.config["XLSX"]
            self.xlsx_file_path = xlsx_section.get("file_path", "")
            
            # 解析显示的列
            display_cols = xlsx_section.get("display_columns", "")
            self.display_columns = [col.strip() for col in display_cols.split(",") if col.strip()]
            
            # 解析筛选条件
            filter_str = xlsx_section.get("filter_conditions", "{}")
            try:
                import ast
                self.filter_conditions = ast.literal_eval(filter_str)
            except (ValueError, SyntaxError):
                self.filter_conditions = {}
            
            # 解析窗口大小和布局配置
            self.window_width = int(xlsx_section.get("window_width", "800"))
            self.window_height = int(xlsx_section.get("window_height", "600"))
            self.checkbox_cols_per_row = int(xlsx_section.get("checkbox_cols_per_row", "4"))
            self.filter_cols_per_row = int(xlsx_section.get("filter_cols_per_row", "3"))

    def save_config(self) -> None:
        """保存配置到文件"""
        # 更新配置
        if "XLSX" not in self.config:
            self.config["XLSX"] = {}
        
        self.config["XLSX"]["file_path"] = self.xlsx_file_path or ""
        self.config["XLSX"]["display_columns"] = ",".join(self.display_columns)
        self.config["XLSX"]["filter_conditions"] = str(self.filter_conditions)
        
        # 写入文件
        with open(self.config_file, "w", encoding="utf-8") as configfile:
            self.config.write(configfile)

    def set_xlsx_config(self, file_path: str, display_columns: List[str], filter_conditions: Dict[str, Any], 
                        window_width: int = None, window_height: int = None, 
                        checkbox_cols_per_row: int = None, filter_cols_per_row: int = None) -> None:
        """设置xlsx配置并保存"""
        self.xlsx_file_path = file_path
        self.display_columns = display_columns
        self.filter_conditions = filter_conditions
        
        # 更新窗口大小和布局配置（如果提供了新值）
        if window_width is not None:
            self.window_width = window_width
        if window_height is not None:
            self.window_height = window_height
        if checkbox_cols_per_row is not None:
            self.checkbox_cols_per_row = checkbox_cols_per_row
        if filter_cols_per_row is not None:
            self.filter_cols_per_row = filter_cols_per_row
        
        self.save_config()

    def get_xlsx_config(self) -> tuple[Optional[str], List[str], Dict[str, Any], int, int, int, int]:
        """获取xlsx配置"""
        return (self.xlsx_file_path, self.display_columns, self.filter_conditions,
                self.window_width, self.window_height, self.checkbox_cols_per_row, self.filter_cols_per_row)

    def config_exists(self) -> bool:
        """检查配置文件是否存在且有有效配置"""
        return (os.path.exists(self.config_file) and 
                self.xlsx_file_path and 
                os.path.exists(self.xlsx_file_path))


# 单例模式，便于全局访问
_config_manager: Optional[ConfigManager] = None


def get_config_manager() -> ConfigManager:
    """获取配置管理器实例"""
    global _config_manager
    if _config_manager is None:
        _config_manager = ConfigManager()
    return _config_manager